!
!   ROBUSTMEAN1 -  Library functions to robust estimation of the mean.
!               -  advanced version of the ROBMEAN procedure
!                  (more output parameters)
!
! $Id$
!-----------------------------------------------------------------------------

       Subroutine RobustMean1(array, n, mean, median, mode, sig, skew )

       use MQuick
       use MMModule

       use cutfun
       use RobMean

! -----------------------------------------------------------------
! this crucial parameter control use original Stetson's method
! for robust estimator of mean if NEWSTAT = .false.
!
! for new (may :-) estimator use NEWSTAT = .true.
       logical, parameter :: NEWSTAT = .true.
! -----------------------------------------------------------------

       Integer :: n,i
       Real :: array(n), mean, sig, median, mode, skew, pom(n)

! Input: 
!      array ... data
!
! Output:
!      n     ... No. of data used to estimation (after clip)
!      mean ... resulting mean
!      sig  ... estimation of the standart deviation
!

       if( NEWSTAT ) then
          n = size(array)
          pom = array(1:n)
          call am1(n,pom,mean,sig,hampel,dhampel,50,i)
          median = mean; mode = mean; skew = 0.0; sig=sig*sqrt(1.0*n)
!          write(*,*) "status=",i," mean,sig,n=",mean,sig,n
       endif

       if( .not. NEWSTAT )then
          n = size(array)
          Call QuickSort(array)

          if( n > MINARRAY ) then    ! normal case

             Call MMM(n, array, 1e10, mean, median, mode, sig, skew)  

          else                       ! pathological case - a few data points
                 
             mean = 0.5*(array((n + 1)/2) + array(n/2 + 1))    
             sig = 0.0
  
          endif
       endif
!	write(*,*) "mean,sig=",mean,sig

       End
